package com.axend.aerosense.common.util;

import com.axend.aerosense.common.BuildConfig;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.connect.bean.BleMessageEntity;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.utils.ThreadPoolUtils;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.connect.DeviceConnectManager;
import com.axend.aerosense.common.connect.bean.BleMsgEntity;
import com.axend.aerosense.common.connect.bean.BleMsgTag;
import com.axend.aerosense.common.connect.bean.BleNotifyEntity;
import com.axend.aerosense.common.connect.bean.DeviceConnectType;
import com.axend.aerosense.common.connect.bean.MessageEntity;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

public class SendMessageUtil {

    private final static long delay = 1500;

    private DeviceConnectManager connectManager;
    private ConcurrentLinkedQueue<MessageEntity> wifiModeMessageQueue;
    private ConcurrentLinkedQueue<BleMsgEntity> bleModeMessageQueue;
    private DeviceConnectType connectType;
    private String radarTcpServer;

    private volatile boolean run = true;

    public SendMessageUtil(DeviceConnectManager connectManager, DeviceConnectType connectType) {
        this.connectManager = connectManager;
        this.connectType = connectType;
        radarTcpServer = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.RADAR_TCP_SERVICE_ADDRESS, UrlApi.radarTcpServerUrl);
        if (BuildConfig.DEBUG) {
            radarTcpServer = UrlApi.getRadarTcpServerUrl();
        }
        if (isWifiMode()){
            wifiModeMessageQueue = new ConcurrentLinkedQueue<>();
        }else {
            bleModeMessageQueue = new ConcurrentLinkedQueue<>();
        }
    }

    /**
     * 最后设置联网信息，雷达会断开连接
     * @param wifiInfoMessageEntity
     */
    public void initQueue(MessageEntity wifiInfoMessageEntity){
        run = true;
        clear();
        wifiModeMessageQueue.offer(new MessageEntity(MessageEntity.MsgTag.getID));
        wifiModeMessageQueue.offer(new MessageEntity(MessageEntity.MsgTag.setDeviceIPAndPort, radarTcpServer));
        wifiModeMessageQueue.offer(new MessageEntity(MessageEntity.MsgTag.getHardwareVersion));
        //最后添加wifi信息
        wifiModeMessageQueue.offer(wifiInfoMessageEntity);
    }

    /**
     * 最后设置服务器ip和端口，雷达会断开连接
     */
    public void initQueue(String ssid, String password, RadarType radarType){
        run = true;
        clear();
        bleModeMessageQueue.offer(new BleMsgEntity(BleMsgTag.RESET_DEVICE, radarType));
        bleModeMessageQueue.offer(new BleMsgEntity(BleMsgTag.GET_DEVICE_ID, radarType));
        bleModeMessageQueue.offer(new BleMsgEntity(
                BleMsgTag.SET_NETWORK_INFO,
                radarType,
                ssid + "," + password));
        // 最后添加服务器信息
        bleModeMessageQueue.offer(new BleMsgEntity(BleMsgTag.SET_SERVER_INFO, radarType, radarTcpServer));
    }

    public void startSend(){
        ThreadPoolUtils.getInstance()
                .execute(()->{
                    if(isWifiMode()){
                        wifiSend();
                    }else {
                        bleSend();
                    }
                });
    }

    public void stopSend(){
        run = false;
    }

    public void executed(){
        if (isWifiMode()){
            if (null != wifiModeMessageQueue){
                wifiModeMessageQueue.poll();
            }
        }else {
            if (null != bleModeMessageQueue){
                bleModeMessageQueue.poll();
            }
        }
    }

    public void executed(BleNotifyEntity entity){
        if (!isWifiMode()){
            //软重启命令只发一次，这里不需要移除
            if (null != bleModeMessageQueue && entity.getTag() != BleMsgTag.RESET_DEVICE){
                bleModeMessageQueue.poll();
            }
        }
    }

    public boolean isEmpty(){
        if (isWifiMode()){
            if (null != wifiModeMessageQueue){
                return wifiModeMessageQueue.isEmpty();
            }
        }else {
            if (null != bleModeMessageQueue){
                return bleModeMessageQueue.isEmpty();
            }
        }
        return true;
    }

    public void clear(){
        if (isWifiMode()){
            if (null != wifiModeMessageQueue){
                wifiModeMessageQueue.clear();
            }
        }else {
            if (null != bleModeMessageQueue){
                bleModeMessageQueue.clear();
            }
        }
    }

    private void bleSend(){
        while (run && !bleModeMessageQueue.isEmpty()){
            try {
                TimeUnit.MILLISECONDS.sleep(delay);
                BleMsgEntity bleMessageEntity = bleModeMessageQueue.peek();
                if (null != bleMessageEntity){
                    connectManager.sendMessage(bleMessageEntity);
                    //软重启命令只发一次，发完就移除
                    if (bleMessageEntity.getTag() == BleMsgTag.RESET_DEVICE){
                        bleModeMessageQueue.poll();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void wifiSend(){
        while (run && !wifiModeMessageQueue.isEmpty()){
            try {
                TimeUnit.MILLISECONDS.sleep(delay);
                MessageEntity wifiMessageEntity = wifiModeMessageQueue.peek();
                if (null != wifiMessageEntity){
                    connectManager.sendMessage(wifiMessageEntity);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 是否为Wifi连接方式
     * @return
     */
    private boolean isWifiMode(){
        return connectType == DeviceConnectType.TYPE_WIFI;
    }

}
